import type { ZhiHuQuestionElements } from '../../../../../../../types/constants/personalization/zhi_hu_question'
import type { ThemeType } from '../../../../../../../types/interfaces'
import { TieBarThemeService } from '../../../../../../../lib/abstract'
import { ElementManager } from '../../../../../../../lib/element_manager'
import { PageHandler } from '../../../../../../../lib/page_handler'
import { ZhiHuQuestionPageType } from '../../../../../../../lib/page_handler/platform/zhi_hu_question/types'
import {
  UNDEFINED_PAGE_TYPE,
  UNDEFINED_PAGE_TYPE_TIPS,
} from '../../../../../../../lib/page_handler/type'
import { ToolKit } from '../../../../../../../lib/utils/toolkit'
import { AnswerNavigator } from '../../../../../../../module/page_enhancer/navigation/answer_navigator'
import {
  AppStyleCollections,
  BODY_SELECTOR,
  generateHideSelector,
  logger,
  loggerDeduplicator,
  PLATFORM_PAGE_TYPES,
  SUPPORTED_PLATFORMS,
} from '../../../../../../../types/constants'
import { ZhiHuQuestionAnswerPage } from './page/answer'
import { ZhiHuQuestionCommonPage } from './page/common'
import { ZhiHuQuestionQuestionPage } from './page/question'

/**
 * 页面处理器
 */
const PAGE_HANDLERS: Partial<Record<ZhiHuQuestionPageType, any>> = {
  [ZhiHuQuestionPageType.Question]: ZhiHuQuestionQuestionPage,
  [ZhiHuQuestionPageType.Answer]: ZhiHuQuestionAnswerPage,
}

export class ZhiHuQuestionThemeService extends TieBarThemeService {
  readonly name: string = 'ZhiHuQuestionTheme'
  readonly platformPageType: string = PLATFORM_PAGE_TYPES.TIEBAR.value
  private static instance: ZhiHuQuestionThemeService
  private readonly pageHandler: PageHandler = PageHandler.getInstance()
  private readonly elementManager: ElementManager = ElementManager.getInstance()
  private currentPageType: ZhiHuQuestionPageType | 'default' = this.pageHandler.pages.zhiHuQuestion.pageType

  declare readonly elements: ZhiHuQuestionElements
  private readonly commonPage: ZhiHuQuestionCommonPage = ZhiHuQuestionCommonPage.getInstance()
  readonly wrapperSelector: string = BODY_SELECTOR

  constructor() {
    super(SUPPORTED_PLATFORMS.ZHI_HU_QUESTION)

    this.updateElementStylesForTheme()
  }

  /**
   * 获取单例实例
   */
  static getInstance(): ZhiHuQuestionThemeService {
    if (!ZhiHuQuestionThemeService.instance) {
      ZhiHuQuestionThemeService.instance = new ZhiHuQuestionThemeService()
    }
    return ZhiHuQuestionThemeService.instance
  }

  /**
   * 批量初始化页面样式
   */
  updateElementStylesForTheme(): void {
    // 通用样式初始化
    this.commonPage.init()

    // 动态获取当前页面处理器并初始化
    const PageHandlerClass = PAGE_HANDLERS[this.currentPageType as ZhiHuQuestionPageType]

    if (PageHandlerClass) {
      PageHandlerClass.getInstance().init()
    }
    else if (this.currentPageType === UNDEFINED_PAGE_TYPE) {
      loggerDeduplicator.warn(UNDEFINED_PAGE_TYPE_TIPS)
    }
    else {
      logger.warn(`未找到 ${this.currentPageType} 页面的处理器`)
    }
  }

  platformStyleVar(_theme: ThemeType): string {
    return ``
  }

  getPageStyles(_theme: ThemeType): string {
    return `
/* 修复官方弹窗打开后导致的页面偏移 */    
html {
  margin-right: unset !important;
  overflow: auto !important;
}

${BODY_SELECTOR} {
  background-color: var(${this.themeVarService.tieBar.default.background}) !important;
  padding-right: unset !important;
    
  &${ToolKit.serviceAlert.generateUserAlertSelector()} {
    /* 修复弹窗打开并隐藏滚动条后固定元素的居中问题 */
    ${AppStyleCollections.Module.ANSWER_NAVIGATOR.selector} {
      margin-left: ${ToolKit.browser.platform.getScrollbarOffset(true)} !important;
    }
  }
  
  /* 没有页眉时移除文章上边距 */
  &:has(${generateHideSelector('header')}) .QuestionHeader {
    margin-top: 0 !important;
  }
}

/* 修复回答导航栏与问题容器的间距问题 */
${this.elementManager.ScriptNavigatorSelector} {
  .QuestionHeader {
    margin-top: ${AnswerNavigator.DOM_HEIGHT} !important;
  }
}
`
  }

  getMainStyles(theme: ThemeType): string {
    // 1. 通用样式
    const commonStyles = this.commonPage.getMainStyles()

    // 2. 动态获取当前页面样式
    let pageStyles = ''
    const PageHandlerClass = PAGE_HANDLERS[this.currentPageType as ZhiHuQuestionPageType]

    if (PageHandlerClass) {
      pageStyles = PageHandlerClass.getInstance().getMainStyles(theme)
    }

    return `
  /* ===================== 【页面】通用样式 ===================== */   
  ${commonStyles}
  /* 关注按钮样式 */
  ${this.getFollowButtonStyles(theme)}
  /* 图片样式（包含回答内容、评论内容） */
  ${this.getImageStyles(theme, '.RichContent #content figure img, .Comments-container .CommentContent .comment_img >')}
  /* ===================== 【页面】独立样式 ===================== */
  ${pageStyles}
`
  }

  getPatchedStyles(_theme: ThemeType): string {
    return `
/* 隐藏关注按钮 */
.AnswerItem-authorInfo .FollowButton {
  display: none !important;
}
`
  }

  getFixedStyles(_theme: ThemeType): string {
    return ``
  }
}
